package com.hmall.order.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmall.common.client.ItemClient;
import com.hmall.common.pojo.Item;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class OrderRabbitListener {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ItemClient itemClient;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "delay.queue", durable = "true"),
            exchange = @Exchange(name = "delay.direct", delayed = "true"),
            key = "delay"
    ))
    public void checkQueueOrderId(String orderId) throws Exception {
        log.info("检查超时订单-接收到的订单id" + orderId);
        Order order = orderMapper.selectById(Long.valueOf(orderId));
        if (order == null) {
            throw new Exception("订单" + orderId + "不存在");
        }
        //检查订单是否为未支付状态
        if (order.getStatus() == 1) {
            //订单设置为取消状态
            order.setStatus(5);
            //获取订单详情对象
            //List<OrderDetail> orderDetails = orderDetailMapper.findByOrderId(Long.valueOf(orderId));
            LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(OrderDetail::getOrderId,Long.valueOf(orderId));
            List<OrderDetail> orderDetails = orderDetailMapper.selectList(queryWrapper);
            //检查订单详情
            if (orderDetails == null || orderDetails.size() == 0) {
                throw new Exception("订单" + orderId + "访问出错");
            }
            orderDetails.forEach(orderDetail -> {
                //获取商品Item对象
                Item item = itemClient.getById(orderDetail.getItemId());
                int num = orderDetail.getNum();
                item.setStock(item.getStock() + num);
                item.setSold(item.getSold() - num);
                //修改商品库存
                itemClient.updata(item);
            });
            orderMapper.updateById(order);
        }

    }
}
